package it.unisannio.lesim.util;

import it.unisannio.lesim.util.exception.ConnectionPoolException;
import java.util.*;
import java.sql.*;

/**
 *
 * @author Marco Calisti
 * @author Antonio Cuomo
 * @author Rocco Mazzeo
 * @author Francesco Pacilio
 * 
 */

public class ConnectionPool {

    private static ConnectionPool connectionPool = null;
    private Vector freeConnections;
    private String dbUrl;
    private String dbDriver;
    private String dbLogin;
    private String dbPassword;

    private ConnectionPool() throws ConnectionPoolException {
        freeConnections = new Vector();
        loadParameters();
        loadDriver();
    }

    private void loadParameters() {
        dbUrl = "jdbc:mysql://localhost/sipana";
        dbDriver = "com.mysql.jdbc.Driver";
        dbLogin = "root";
        dbPassword = "root";
    }

    private void loadDriver() throws ConnectionPoolException {
        try {
            java.lang.Class.forName(dbDriver);
        } catch (Exception e) {
            throw new ConnectionPoolException();
        }
    }

    public static synchronized ConnectionPool getConnectionPool()
            throws ConnectionPoolException {
        if (connectionPool == null) {
            connectionPool = new ConnectionPool();
        }
        return connectionPool;
    }

    public synchronized Connection getConnection() throws ConnectionPoolException {
        Connection connection;

        if (freeConnections.size() > 0) {
            connection = (Connection) freeConnections.firstElement();
            freeConnections.removeElementAt(0);
            try {
                if (connection.isClosed()) {
                    connection = getConnection();
                }
            } catch (SQLException e) {
                connection = getConnection();
            }
        } else {
            connection = newConnection();
        }

        return connection;
    }

    private Connection newConnection() {
        Connection con = null;

        try {
            con = DriverManager.getConnection(dbUrl, dbLogin, dbPassword);
        } catch (SQLException e) {
            new ConnectionPoolException(e.getMessage());
        }

        return con;
    }

    public synchronized void releaseConnection(Connection con) {
        freeConnections.add(con);
    }
    
}


    
